<script setup lang="ts">
import { nextTick, ref, shallowRef, computed } from "vue";
import { useColumns } from "./columns";
import "plus-pro-components/es/components/search/style/css";
import { addDialog } from "@/components/ReDialog";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import UploadIcon from "~icons/ri/upload-2-line?width=26&height=26";
import Plus from "~icons/ep/plus";
import { uploadImage } from "@/api/common";
import {
  fixImageUrl,
  handleImagesUpload,
  handleImagesUploadEditor,
  imageFile
} from "@/utils/common";
import { addNews, setNews, getNews } from "@/api/news";
import "@wangeditor/editor/dist/css/style.css";
defineOptions({
  name: "OperateAcadamy"
});
import {
  type PlusColumn,
  type FieldValues,
  PlusDialogForm,
  PlusSearch
} from "plus-pro-components";
import {
  type Action,
  genFileId,
  ElMessageBox,
  ElMessage,
  UploadInstance,
  UploadProps,
  UploadRawFile
} from "element-plus";

import { useMenu } from "@/utils/power";
const power = useMenu(["add", "edit"]);

const mode = "default";
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const toolbarConfig: any = {}; // { excludeKeys: "fullScreen" };
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      customUpload: async (file: File, insertFn) => {
        try {
          const res = await handleImagesUploadEditor(file);
          insertFn(res.data, "", res.data);
        } catch (error) {
          console.error(error);
        }
      }
    },
    insertVideo: {
      onInsertedVideo: async video => {
        if (video == null) return;
      }
    },
    uploadVideo: {
      customUpload: async (file: File, insertFn) => {
        try {
          const res = await handleImagesUploadEditor(file);
          insertFn(res.data, "");
        } catch (error) {
          console.error(error);
        }
      }
    }
  }
};
const handleCreated = editor => {
  // 记录 editor 实例，重要！
  editorRef.value = editor;
};

const tableRef = ref();

const defaultSearchState = ref({
  type: 3
});
const searchValues = ref({
  type: 3
});

const searchColumns: PlusColumn[] = [
  {
    label: "搜索",
    width: 200,
    prop: "keyWord",
    valueType: "copy",
    tooltip: "请输入搜索关键词"
  }
  // {
  //   label: "新闻类目",
  //   prop: "type",
  //   valueType: "select",
  //   options: [
  //     {
  //       label: "汉诺学院",
  //       value: 3,
  //       color: "red"
  //     }
  //   ]
  // }
];

const rules = {
  title: [
    {
      required: false,
      message: "新闻标题必填"
    }
  ],
  banner: [
    {
      required: false,
      message: "新闻封面必填"
    }
  ],
  content: [
    {
      required: true,
      message: "新闻内容必填"
    }
  ]
};
const previewImageUrl = ref();
const previewImageName = ref();
const showPreviewImage = ref(false);

const bannerImageRef = ref<UploadInstance>();
const edit = ref(false);
const confirmLoading = ref(false);
const visible = ref(false);
const values = ref<FieldValues>({});
const formRef = ref();
const formColumns: PlusColumn[] = [
  {
    label: "标题",
    prop: "title",
    valueType: "input",
    tooltip: "请输入标题"
  },
  {
    label: "新闻封面",
    prop: "banner",
    valueType: "img",
    tooltip: "请输入封面图片地址"
  },
  {
    label: "新闻类目",
    prop: "type",
    valueType: "select",
    options: [
      {
        label: "汉诺学院",
        value: 3,
        color: "red"
      }
    ]
  },
  {
    label: "状态",
    prop: "status",
    valueType: "radio",
    options: [
      {
        label: "发布",
        value: 1,
        color: "red"
      },
      {
        label: "草稿",
        value: 2,
        color: "red"
      }
    ]
  },
  {
    label: "新闻内容",
    prop: "content"
  }
];

const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  loadData,
  onSizeChange,
  onKeywordChange,
  onCurrentChange
} = useColumns();

const columnsRef = computed(() => {
  if (power.value.edit) {
    return columns;
  }
  const columnsCopy = [...columns];
  return columnsCopy.slice(0, -1);
});

const handleSearch = (value: any) => {
  console.log(value, "search");
  onKeywordChange(value);
};
const handleReset = value => {
  console.log("reset");
  onKeywordChange(value);
};

const handleChange = (value: any, target: any) => {
  console.log("change", value);
  if (target.prop == "keyWord") {
    return;
  }
  onKeywordChange(value);
};

const editClick = async row => {
  console.log(
    "%crow===详情>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
  try {
    const res = await getNews(row.newsId);
    const data = res.data;
    values.value = data;
    edit.value = true;
    visible.value = true;
    // setTimeout(() => {
    //   editorRef.value?.dangerouslyInsertHtml(data.content);
    // }, 100);
    // editorRef.value?.dangerouslyInsertHtml(data.content);
  } catch (error) {
    console.error(error);
  }
};
const add = () => {
  edit.value = false;
  values.value = { content: "" };
  visible.value = true;
};
const handleSubmit = async (value: FieldValues) => {
  const updatedValues = { ...values.value };
  const newContent = updatedValues.content.replace(
    /width="(?:auto|\d+)"/g,
    'width="100%"'
  );
  console.log("html", updatedValues.content, newContent);
  updatedValues.content = newContent;

  confirmLoading.value = true;
  if (edit.value) {
    try {
      await setNews(updatedValues);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  } else {
    try {
      await addNews(updatedValues);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      editorRef.value?.clear();
      loadData();
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  }
};
const handleCancel = () => {
  console.log("取消");
  editorRef.value?.clear();
};
const handleBannerImageSuccess: UploadProps["onSuccess"] = (res, file) => {
  values.value.banner = res.data;
  console.log(
    "%cfile===>>>",
    "color: MidnightBlue; font-size: 20px;",
    res,
    file
  );
};
const handleBannerImageRemove: UploadProps["onRemove"] = (file, files) => {
  values.value.banner = undefined;
  console.log(
    "%cfile===>>>",
    "color: MidnightBlue; font-size: 20px;",
    file,
    files
  );
};
/// 超出limit限制 先清空文件列表再执行上传
const handleBannerImageExceed: UploadProps["onExceed"] = files => {
  bannerImageRef.value?.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  bannerImageRef.value?.handleStart(file);
  bannerImageRef.value?.submit();
};
const handlePreviewImage: UploadProps["onPreview"] = file => {
  previewImageName.value = file.name;
  previewImageUrl.value = file.url;
  showPreviewImage.value = true;
};
</script>

<template>
  <ElCard>
    <template #header>
      <ElPageHeader :icon="null">
        <template #title>
          <h3>汉诺学院</h3>
        </template>
        <template v-if="power.add" #extra>
          <div class="flex flex-row items-end justify-end">
            <el-button type="primary" @click="add">
              <el-icon :size="15" color="#fff">
                <IconifyIconOffline :icon="Plus" />
              </el-icon>
              添加新闻
            </el-button>
          </div>
        </template>
        <PlusSearch
          v-model="searchValues"
          :defaultValues="defaultSearchState"
          class="mt-5"
          :columns="searchColumns"
          @reset="handleReset"
          @search="handleSearch"
          @change="handleChange"
        />
      </ElPageHeader>
    </template>
    <pure-table
      ref="tableRef"
      showOverflowTooltip
      border
      adaptive
      :fit="true"
      :adaptiveConfig="adaptiveConfig"
      row-key="id"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columnsRef"
      :pagination="pagination"
      @page-size-change="onSizeChange"
      @page-current-change="onCurrentChange"
    >
      <template #operation="{ row }">
        <el-button
          v-if="power.edit"
          type="primary"
          size="small"
          @click="editClick(row)"
        >
          编辑
        </el-button>
      </template>

      <template #banner="{ row, index }">
        <el-image
          preview-teleported
          loading="lazy"
          :src="row.banner"
          :preview-src-list="dataList.map(v => v.banner)"
          :initial-index="index"
          fit="cover"
          class="w-[50px] h-[50px]"
        />
      </template>
    </pure-table>
    <PlusDialogForm
      ref="formRef"
      v-model:visible="visible"
      v-model="values"
      :form="{ columns: formColumns, rules, labelWidth: 120 }"
      :dialog="{ confirmLoading }"
      :title="edit ? '编辑新闻' : '添加新闻'"
      @confirm="handleSubmit"
      @cancel="handleCancel"
    >
      <template #plus-field-banner>
        <el-upload
          ref="bannerImageRef"
          drag
          :auto-upload="true"
          list-type="picture-card"
          :limit="1"
          :http-request="handleImagesUpload"
          :file-list="
            values.banner && values.banner.length > 0
              ? imageFile(values.banner)
              : []
          "
          :on-success="handleBannerImageSuccess"
          :on-remove="handleBannerImageRemove"
          :on-preview="handlePreviewImage"
          :on-exceed="handleBannerImageExceed"
        >
          <div>
            <UploadIcon class="m-auto mb-2" />
            可点击或拖拽上传
          </div>
        </el-upload>
      </template>
      <template #plus-field-content>
        <div class="wangeditor">
          <Toolbar
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
            style="border-bottom: 1px solid #ccc"
          />
          <Editor
            v-model="values.content"
            :defaultConfig="editorConfig"
            :mode="mode"
            style="height: 500px; overflow-y: hidden"
            @onCreated="handleCreated"
          />
        </div>
      </template>
    </PlusDialogForm>
    <el-dialog v-model="showPreviewImage">
      <img w-full :src="previewImageUrl" :alt="previewImageName" />
    </el-dialog>
  </ElCard>
</template>

<style scoped>
:deep(.el-descriptions),
:deep(.el-descriptions__table tr) {
  --el-card-bg-color: transparent !important;
  --el-fill-color-blank: transparent !important;
  background: transparent !important;
}
.wrap-text {
  white-space: normal !important; /* 允许自动换行 */
  word-break: break-all; /* 强制换行 */
}
:deep(video) {
  width: 100% !important;
}
</style>
